<template>
  <div class="personnel-passage-record bg-background text-foreground p-4">
    <h2 class="mb-4 text-2xl font-bold">人员异常分布报警</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchPersonnel" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2" style="display: flex; justify-content: space-between;">
      <div>

        <el-button @click="deleteRecord" style="width: 75px; height: 30px;">删除</el-button>
        <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
      </div>
      <div>
        <el-button @click="showSettings = true" type="primary" style="width: 75px; height: 30px;">设置</el-button>
      </div>

    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedPersonnelData" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">

        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>

        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="EVENT_CODE" label="事件编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EVENT_TYPE" label="事件类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EVENT_DESCRIPTION" label="事件描述" header-align="center" align="center"></el-table-column>
        <el-table-column prop="MONITORING_EQUIPMENT" label="监测设备" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AREA" label="区域" header-align="center" align="center"></el-table-column>
        <el-table-column prop="OCCURRENCE_DATE" label="发生日期" header-align="center" align="center">
          <template #default="scope">
            {{ dayjs(scope.row.OCCURRENCE_DATE).format('YYYY-MM-DD HH:mm:ss') }}

          </template>
        </el-table-column>
        <el-table-column prop="REMARKS" label="备注" header-align="center" align="center"></el-table-column>
      </el-table>
    </div>

    <!-- Pagination -->
    <div class="bg-card text-card-foreground border-border flex items-center justify-between border-t px-4 py-3 sm:px-6">

      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>
    <!--  -->
    <el-dialog class="dialog-from dialog-set" v-model="showSettings" title="人员异常分布规则设置" width="650" destroy-on-close
      align-center>
      <div>
        <div class="tablename">
          <div style="width: 10px; height: 10px; background-color:#02a7f0;margin-right: 10px;    border-radius: 50%;">
          </div>
          <span>人员异常聚集</span>
        </div>
        <div>
          <span style="margin-right: 5px;">限制区域内超过人数</span><el-input style="width: 70px;"
            v-model="setFrom.SPEEDING"></el-input><span style="margin-left: 5px;">人</span>
        </div>
        <div style="margin-top: 15px;">
          <span>通知对象：</span>
          <el-select style="width: 150px;" v-model="setFrom.PARKING" placeholder="请选择">
            <el-option value="值班A组-张三">值班A组-张三 </el-option>
            <el-option value="值班B组-李四">值班B组-李四 </el-option>

          </el-select>
        </div>
        <div>
          <el-radio-group v-model="setFrom.FOLLOW_BEGIN" @change="changeradio">
            <el-radio value="1">启用</el-radio>
            <el-radio value="2">关闭</el-radio>
          </el-radio-group>
        </div>
        <el-divider />
      </div>
      <div>
        <div class="tablename">
          <div style="width: 10px; height: 10px; background-color:#02a7f0;margin-right: 10px;    border-radius: 50%;">
          </div>
          <span>人员入侵越界报警</span>
        </div>
        <div>
          <span style="margin-right: 10px;">限制区域：</span>
          <span>纬度：</span>
          <el-input style="width: 70px;"></el-input>
          <span>---</span>
          <el-input style="width: 70px;"></el-input>
          <span style="margin-left: 10px;">纬度：</span>
          <el-input style="width: 70px;"></el-input>
          <span>---</span>
          <el-input style="width: 70px;"></el-input>
        </div>
        <div style="margin-top: 15px;">
          <span>通知对象：</span>
          <el-select style="width: 150px;" v-model="setFrom.PARKING" placeholder="请选择">
            <el-option value="值班A组-张三">值班A组-张三 </el-option>
            <el-option value="值班B组-李四">值班B组-李四 </el-option>
          </el-select>
        </div>
        <div>
          <el-radio-group v-model="setFrom.FOLLOW_BEGIN">
            <el-radio value="1">启用</el-radio>
            <el-radio value="2">关闭</el-radio>
          </el-radio-group>
        </div>
        <el-divider />
      </div>
      <div>
        <div class="tablename">
          <div style="width: 10px; height: 10px; background-color:#02a7f0;margin-right: 10px;    border-radius: 50%;">
          </div>
          <span>人员异常聚集</span>
        </div>
        <div>
          <div>
            <span>工作日时间：</span>
            <el-input type="time" style="width: 70px;"></el-input>
            <span style="margin:0px 10px 0px 25px;">---</span>
            <el-input type="time" style="width: 70px;"></el-input>
          </div>
          <div style="margin-top: 15px;">
            <span>节假日时间：</span>
            <el-input type="time" style="width: 70px;"></el-input>
            <span style="margin:0px 10px 0px 25px;">---</span>
            <el-input type="time" style="width: 70px;"></el-input>
          </div>
        </div>
        <div style="margin-top: 15px;">
          <span>通知对象：</span>
          <el-select style="width: 150px;" v-model="setFrom.PARKING" placeholder="请选择">
            <el-option value="值班A组-张三">值班A组-张三 </el-option>
            <el-option value="值班B组-李四">值班B组-李四 </el-option>
          </el-select>
        </div>
        <div>
          <el-radio-group v-model="setFrom.FOLLOW_BEGIN">
            <el-radio value="1">启用</el-radio>
            <el-radio value="2">关闭</el-radio>
          </el-radio-group>
        </div>
        <el-divider />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="setSubmit">确认</el-button>
          <el-button @click="showSettings = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
import { dayjs } from "element-plus"
const { proxy } = getCurrentInstance()
import { exportData } from '#/utils/exportfile.js'
const apiBaseUrl = ref(proxy.$currentUrl + '/api/personnel_distribution_alarm')

const rowKey = (row) => row.ID // 设置行的唯一标识

const search = ref({
  EVENT_CODE: '',
  EVENT_TYPE: '',
})
const table = ref()
const showSettings = ref(false);
const formItems = ref([
  {
    label: '事件编码：',
    model: 'EVENT_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '事件类型：',
    model: 'EVENT_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '全部', value: '' },
      { label: '非法闯入', value: '非法闯入' },
      { label: '异常聚集', value: '异常聚集' },
    ],
  },
])






const personnelData = ref([])

const selectAll = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpToPage = ref(1)
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const importFile = ref(null)

const recordId = ref('')
const currentRecord = ref(null)

const deleteId = ref('')
const deleteUpdateBy = ref('')
const selectedItem = ref(null)

const allRecords = ref([])

const totalItems = computed(() => allRecords.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)
const endIndex = computed(() =>
  Math.min(startIndex.value + pageSize.value, totalItems.value),
)
const displayedPages = computed(() => {
  const range = 2
  const start = Math.max(1, currentPage.value - range)
  const end = Math.min(totalPages.value, currentPage.value + range)
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

const setFrom = ref({
  SPEEDING: 0,
  PARKING: '',
  FOLLOW_BEGIN: '',
  FOLLOW_END: '',
  TIME_BEGIN: '',
  TIME_END: '',
})
const setSubmit = () => {
  alert('设置成功');
  showSettings.value = false;
}


const changeradio = (row) => {
  console.log(row)
}

const displayedPersonnelData = computed(() => {
  // const start = (currentPage.value - 1) * pageSize.value;
  // const end = start + pageSize.value;
  // return filteredPersonnelData.value.slice(start, end);
  return allRecords.value.slice(startIndex.value, endIndex.value)
})



const searchPersonnel = async () => {

  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: search.value,
    })
    allRecords.value = response.data
    selectedIds.value = []
    loading.value = false
  } catch (error) {
    console.error('获取所有记录失败:', error)
    alert(
      '获取所有记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const resetSearch = () => {

  search.value = {
    EVENT_CODE: '',
    EVENT_TYPE: '',
  }
  searchPersonnel()
}



const selectedIds = ref([])
const deleteRecord = async () => {

  if (selectedIds.length === 0) {
    alert('请选择要删除的设备')
    return
  }

  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 个设备吗？`)) {
    console.log(selectedIds.value)
    try {
      await Promise.all(
        selectedIds.value.map((item) =>
          axios.delete(`${apiBaseUrl.value}/${item.ID}`),
        ),
      )
      alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await searchPersonnel()
    } catch (error) {
      console.error('删除设备失败:', error)
      alert('删除设备失败: ' + (error.response?.data?.message || error.message))
    }
  }

}



const changePageSize = () => {
  currentPage.value = 1
}

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

watch(selectAll, (newValue) => {
  personnelData.value.forEach((item) => (item.selected = newValue))
})

// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}

const formRef = ref(null)
const isDialogType = ref('')
const loading = ref(false)
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}

onMounted(() => {
  searchPersonnel()

})








</script>

<style scoped>
:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

.dialog-from :deep(.el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

/* 移除大部分样式，因为现在由 Tailwind 类处理 */
.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}


.input-time-query {
  margin-top: 0;
  border-radius: 5%;
  display: inline-block;
  box-shadow: 0 0 0 1px #dcdfe6;
  width: 180px;
  height: 32px;
}

.input-time-query:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}
</style>
